<template>
  <div class="user-manage">
    <a-form layout="vertical">
      <a-card title="用户管理" :bordered="false">
        <div class="table-operations">
          <a-button type="primary" @click="showAddUser">
            <plus-outlined />添加用户
          </a-button>
          <a-button style="margin-left: 8px" @click="() => fetchUsers()">
            <reload-outlined />刷新
          </a-button>
        </div>

        <a-table
            :columns="columns"
            :data-source="users"
            :loading="loading"
            :pagination="pagination"
            @change="handleTableChange"
            style="margin-top: 16px"
            row-key="username"
        >
          <template #bodyCell="{ column, text, record }">
            <template v-if="column.key === 'role'">
               <a-tag :color="text === 'administrator' ? 'red' : (text === 'operator' ? 'blue' : 'green')">
                 {{ text === 'administrator' ? '管理员' : (text === 'operator' ? '操作员' : '访客') }}
               </a-tag>
             </template>
            <template v-else-if="column.key === 'status'">
              <a-badge :status="text === 'active' ? 'success' : 'default'" :text="text === 'active' ? '启用' : '禁用'" />
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="handleEdit(record)" :disabled="record.username === 'admin'">
                  编辑
                </a-button>
                <a-button type="link" size="small" @click="handleResetPassword(record)">
                  修改密码
                </a-button>
                <a-popconfirm
                  title="确定要删除该用户吗?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="confirmDelete(record)"
                  :disabled="record.username === 'admin'"
                >
                  <a-button type="link" danger size="small" :disabled="record.username === 'admin'">
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </a-form>

    <a-modal v-model:visible="userModalVisible" :title="isEdit ? '编辑用户' : '添加用户'" @ok="handleSubmit"
      @cancel="handleCancel" :confirmLoading="submitting" :destroyOnClose="true">
      <a-form ref="userFormRef" :model="userForm" layout="vertical">
        <a-form-item label="用户名" name="username" :rules="[
          { required: true, message: '请输入用户名' },
          { min: 3, message: '用户名至少3个字符' },
          { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' }
        ]">
          <a-input v-model:value="userForm.username" :disabled="isEdit" placeholder="请输入用户名" />
        </a-form-item>

        <a-form-item v-if="!isEdit" label="密码" name="password" :rules="[
          { required: true, message: '请输入密码' },
          { min: 6, message: '密码至少6个字符' }
        ]">
          <a-input-password v-model:value="userForm.password" placeholder="请输入密码" />
        </a-form-item>

        <a-form-item v-if="!isEdit" label="确认密码" name="confirmPassword" :rules="[
          { required: true, message: '请确认密码' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]">
          <a-input-password v-model:value="userForm.confirmPassword" placeholder="请确认密码" />
        </a-form-item>

        <a-form-item label="用户角色" name="role" :rules="[{ required: true, message: '请选择用户角色' }]">
          <a-radio-group v-model:value="userForm.role" :disabled="isEdit && userForm.username === 'admin'">
            <a-radio value="viewer">访客</a-radio>
            <a-radio value="operator">操作员</a-radio>
            <a-radio value="administrator">管理员</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="状态" name="status" v-if="isEdit">
          <a-radio-group v-model:value="userForm.status" :disabled="userForm.username === 'admin'">
            <a-radio value="active">启用</a-radio>
            <a-radio value="disabled">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:visible="resetPasswordModalVisible" title="修改密码" @ok="confirmResetPassword"
      @cancel="cancelResetPassword" :confirmLoading="submitting" :destroyOnClose="true">
      <a-form ref="resetPasswordFormRef" :model="resetPasswordForm" layout="vertical">
         <a-form-item label="用户名">
           <a-input :value="selectedUser?.username" disabled />
         </a-form-item>
        <a-form-item label="原密码" name="oldPassword" :rules="[
          { required: true, message: '请输入原密码' }
        ]">
          <a-input-password v-model:value="resetPasswordForm.oldPassword" placeholder="请输入原密码" />
        </a-form-item>
        <a-form-item label="新密码" name="newPassword" :rules="[
          { required: true, message: '请输入新密码' },
          { min: 6, message: '密码至少6个字符' }
        ]">
          <a-input-password v-model:value="resetPasswordForm.newPassword" placeholder="请输入新密码" />
        </a-form-item>
        <a-form-item label="确认新密码" name="confirmNewPassword" :rules="[
          { required: true, message: '请确认新密码' },
          { validator: validateResetPasswordConfirm, trigger: 'blur' }
        ]">
          <a-input-password v-model:value="resetPasswordForm.confirmNewPassword" placeholder="请确认新密码" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, reactive, ref, toRefs, onMounted, nextTick } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import { getUsers, createUser, updateUser, deleteUser, changePassword } from '../../api/user';

export default defineComponent({
  name: 'UserManage',
  components: {
    PlusOutlined,
    ReloadOutlined
  },
  setup() {
    const columns = [
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username'
      },
      {
        title: '角色',
        dataIndex: 'role',
        key: 'role',
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
      },
      {
        title: '操作',
        key: 'action',
        width: 200,
      }
    ];

    const state = reactive({
      users: [],
      loading: false,
      userModalVisible: false,
      resetPasswordModalVisible: false,
      submitting: false,
      isEdit: false,
      selectedUser: null,
      userForm: {
        username: '',
        password: '',
        confirmPassword: '',
        role: 'viewer',
        status: 'active'
      },
      resetPasswordForm: {
        oldPassword: '',
        newPassword: '',
        confirmNewPassword: ''
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: total => `共 ${total} 条`
      }
    });

    const userFormRef = ref(null);
    const resetPasswordFormRef = ref(null);

    const validateConfirmPassword = async (rule, value) => {
      if (!state.isEdit && state.userForm.password && value !== state.userForm.password) {
        return Promise.reject('两次输入的密码不一致');
      }
      return Promise.resolve();
    };

    const validateResetPasswordConfirm = async (rule, value) => {
      if (state.resetPasswordForm.newPassword && value !== state.resetPasswordForm.newPassword) {
        return Promise.reject('两次输入的密码不一致');
      }
       return Promise.resolve();
    };

    const fetchUsers = async (page = state.pagination.current, pageSize = state.pagination.pageSize) => {
      state.loading = true;
      try {
        const data = await getUsers({ page: page, page_size: pageSize });
        state.users = data.users || [];
        state.pagination.total = data.total || 0;
        state.pagination.current = data.page || 1;
        state.pagination.pageSize = data.page_size || 10;
      } catch (error) {
        message.error(error.message || '获取用户列表失败');
        state.users = [];
        state.pagination.total = 0;
      } finally {
        state.loading = false;
      }
    };

    const showAddUser = () => {
      state.isEdit = false;
      state.userForm = {
        username: '',
        password: '',
        confirmPassword: '',
        role: 'viewer',
        status: 'active'
      };
       nextTick(() => {
         userFormRef.value?.resetFields();
       });
      state.userModalVisible = true;
    };

    const handleEdit = (user) => {
      state.isEdit = true;
      state.selectedUser = { ...user };
      state.userForm = {
        username: user.username,
        role: user.role,
        status: user.status
      };
       nextTick(() => {
         userFormRef.value?.resetFields(['password', 'confirmPassword']);
         userFormRef.value?.clearValidate();
       });
      state.userModalVisible = true;
    };

    const handleResetPassword = (user) => {
      state.selectedUser = user;
      state.resetPasswordForm = {
        oldPassword: '',
        newPassword: '',
        confirmNewPassword: ''
      };
      nextTick(() => {
        resetPasswordFormRef.value?.resetFields();
      });
      state.resetPasswordModalVisible = true;
    };

    const handleSubmit = async () => {
       try {
        await userFormRef.value?.validate();
        state.submitting = true;
        if (state.isEdit) {
          await updateUser(state.userForm.username, {
            role: state.userForm.role,
            status: state.userForm.status
          });
          message.success('用户信息已更新');
        } else {
          await createUser({
            username: state.userForm.username,
            password: state.userForm.password,
            role: state.userForm.role
          });
          message.success('用户已添加');
        }
        await fetchUsers(state.pagination.current, state.pagination.pageSize);
        state.userModalVisible = false;
      } catch (error) {
         if (error?.message) {
             message.error(error.message || (state.isEdit ? '更新失败' : '添加失败'));
         } else if (error?.errorFields) {
             console.warn('表单校验失败:', error.errorFields);
             message.warning('请检查表单输入');
         } else {
             console.error('未知提交错误:', error);
         }
      } finally {
        state.submitting = false;
      }
    };

    const confirmDelete = async (record) => {
      state.submitting = true;
      try {
        await deleteUser(record.username);
        message.success('用户已删除');
        const currentPage = state.pagination.current;
        const pageSize = state.pagination.pageSize;
        const totalPages = Math.ceil((state.pagination.total - 1) / pageSize);
        const nextPage = (state.users.length === 1 && currentPage > 1 && currentPage > totalPages) ? currentPage - 1 : currentPage;
        await fetchUsers(nextPage, pageSize);
      } catch (error) {
        message.error(error.message || '删除失败');
      } finally {
        state.submitting = false;
      }
    };

    const confirmResetPassword = async () => {
       try {
           await resetPasswordFormRef.value?.validate();
           state.submitting = true;
           await changePassword(
               state.selectedUser.username,
               state.resetPasswordForm.oldPassword,
               state.resetPasswordForm.newPassword
           );
           message.success('密码已修改');
           state.resetPasswordModalVisible = false;
       } catch (error) {
            if (error?.message) {
               message.error(error.message || '修改密码失败');
            } else if (error?.errorFields) {
                console.warn('重置密码表单校验失败:', error.errorFields);
                message.warning('请检查表单输入');
            } else {
                 console.error('未知重置密码错误:', error);
            }
       } finally {
        state.submitting = false;
      }
    };

    const handleCancel = () => {
        userFormRef.value?.resetFields();
        userFormRef.value?.clearValidate();
        state.userModalVisible = false;
        state.selectedUser = null;
    };

    const cancelResetPassword = () => {
        resetPasswordFormRef.value?.resetFields();
        resetPasswordFormRef.value?.clearValidate();
        state.resetPasswordModalVisible = false;
        state.selectedUser = null;
    };

    const handleTableChange = (pagination, filters, sorter) => {
      state.pagination.current = pagination.current;
      state.pagination.pageSize = pagination.pageSize;
      fetchUsers(pagination.current, pagination.pageSize);
    };

    onMounted(() => {
      fetchUsers();
    });

    return {
      columns,
      ...toRefs(state),
      userFormRef,
      resetPasswordFormRef,
      validateConfirmPassword,
      validateResetPasswordConfirm,
      fetchUsers,
      showAddUser,
      handleEdit,
      handleResetPassword,
      handleSubmit,
      handleCancel,
      confirmDelete,
      confirmResetPassword,
      cancelResetPassword,
      handleTableChange
    };
  }
});
</script>

<style scoped>
.user-manage {
  padding: 20px;
}

.table-operations {
  margin-bottom: 16px;
}

.ant-form-item {
  margin-bottom: 16px;
}
</style>
